<template>
  <div style="margin-top:12px;flex:1">
    <a-table size="middle" class="CandidateTable" style="padding: 0 12px" :scroll="{x: true}" :rowKey="record=>record.id" :columns="[...columns, ...fieldsTmp]" :dataSource="data" :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}" :rowClassName="setRowClassName" :pagination="pagination" :loading="loading">
      <template slot="email" slot-scope="text">
        <a :href="`mailto:${text}`" class="blue">{{text}}</a>
      </template>
      <template slot="positionName" slot-scope="text, record">
        <a-tooltip :overlayStyle="{ maxWidth: '400px' }" v-if="text && text.length > 33">
          <template slot="title">
            <span style="white-space:wrap">{{text}}</span>
          </template>
          <p v-if="record.vendorPartnerStatus === 'Y'" class="blue cursor" @click="goPositionDetail(record)">{{text}}</p>
          <p v-else>{{text}}</p>
        </a-tooltip>
        <template v-else>
          <p v-if="record.vendorPartnerStatus === 'Y'" class="blue cursor" @click="goPositionDetail(record)">{{text}}</p>
          <p v-else>{{text}}</p>
        </template>
      </template>
      <template v-for="item in fieldsTmp" :slot="item.key" slot-scope="text, record">
        <p :key="item.key">
          <a-tooltip v-if="text && text.length > 54">
            <template slot="title">
              {{text}}
            </template>
            <span @click="filterField(item, record)" :class="item.hasLink ? 'point': ''">{{text}}</span>
          </a-tooltip>
          <template v-else>
            <span @click="filterField(item, record)" :class="item.hasLink ? 'point': ''">{{text}}</span>
          </template>
        </p>
      </template>
      <template slot="operatorStatus" slot-scope="text, record">
        <template v-if="record.placeFile || record.pending || record.operatorStatus === 'Accepted' || record.operatorStatus === 'Rejected'">
          <span v-if="record.placeFile" class="grey status">{{$t('candidateApplication.placeFile')}}</span>
          <span v-if="record.pending" class="bgBlue status">{{$t('candidateApplication.pending')}}</span>
          <span v-if="record.operatorStatus === 'Accepted'" class="green status">{{$t('candidateApplication.accepted')}}</span>
          <span v-if="record.operatorStatus === 'Rejected'"  class="bgred status">{{$t('candidateApplication.rejected')}}</span>
        </template>
        <span v-else>{{getStatusName(text)}}</span>
      </template>
    </a-table>
    <resume-edit :positionInfo="positionInfo" :visible="isshowResume" @close="(flag) => recommedResume(false, null, flag)" :id="id" :positionId="positionId" :enterpriseId="enterpriseId" :resumeData="resumeData" :resumeId="resumeData.id"/>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
// import { selectTreeList } from '@/api/employingUnit'
import TableOperate from '@/components/SearchList/TableOperate'
import SearchFiled from '@/components/SearchList/SearchFiled'
import ResumeEdit from '@/components/resume/ResumeEdit'
// import {  } from '@/api/resume'
import { applicationList, applicationShowConfig, addOrModifyShowConfig, applicationOperator, recommendQueryConditions, resumeInfo } from '@/api/resume'
import { filterBtn, recordBtn } from '@/util/roles'
const statusColumns = [{
  title: '状态',
  dataIndex: 'operatorStatus',
  key: 'operatorStatus',
  scopedSlots: { customRender: 'operatorStatus' }
}]

const operateBtn = [{
  name: 'candidateApplication.accepted',
  roles: ['NORMAL', 'COMPANY_MANAGER'],
  status: 'operatorStatus',
  statusValN: ['Accepted'],
  id: 'Accepted'
}, {
  name: 'candidateApplication.rejected',
  roles: ['NORMAL', 'COMPANY_MANAGER'],
  status: 'operatorStatus',
  statusValN: ['Rejected'],
  id: 'Rejected'
}, {
  name: 'candidateApplication.pending',
  roles: ['NORMAL', 'COMPANY_MANAGER'],
  status: 'pending',
  statusValN: [true],
  id: 'pending'
}, {
  name: 'candidateApplication.cancel_pending',
  roles: ['NORMAL', 'COMPANY_MANAGER'],
  status: 'pending',
  statusValN: [false],
  singleData: true,
  id: 'cancelPending'
}, {
  name: 'candidateApplication.placeFile',
  roles: ['NORMAL', 'COMPANY_MANAGER'],
  status: 'placeFile',
  statusValN: [true],
  singleData: true,
  id: 'placeOnFile'
}, {
  name: 'common.delete',
  id: 'delete'
}]
const deliveryDateArr = [{
  id: 'all',
  name: 'searchList.dateText'
}, {
  id: '3D',
  name: 'searchList.3D'
}, {
  id: '1W',
  name: 'searchList.1W'
}, {
  id: '1M',
  name: 'searchList.1M'
}, {
  id: '6M',
  name: 'searchList.6M'
}]

export default {
  name: 'CandidateTable',
  components: { TableOperate, SearchFiled, ResumeEdit },
  props: [ 'searchPositionId', 'dataList', 'searchType' ],
  data () {
    return {
      positionInfo: {},
      id: '',
      columns: [
        {
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          key: 'email',
          scopedSlots: { customRender: 'email' }
        },
        {
          title: '电话',
          dataIndex: 'mobile',
          key: 'mobile'
        },
        {
          title: '职位',
          dataIndex: 'positionName',
          key: 'positionName',
          scopedSlots: { customRender: 'positionName' }
        },
        {
          title: '推荐日期',
          dataIndex: 'deliverTime',
          key: 'deliverTime'
        }
      ],
      statusColumns,
      data: [],
      deliveryDateArr,
      operateBtn: null,
      searchListArr: [],
      unFieldList: [],
      unField: {}, // 列表点击后搜索数据
      selectedRowKeys: [],
      selectedRows: [],
      loading: false,
      deliverDate: '',
      resumeField: {}, // 搜索表单数据
      fieldsTmp: [],
      valueFileds: {},
      dateData: null,
      operator: '',
      isshowResume: false,
      positionId: '',
      enterpriseId: '',
      resumeData: {},
      pagination: {
        total: 0,
        simple: true,
        current: 1,
        pageSize: 15,
        onChange: this.changePage
      }
    }
  },
  created () {
    if (this.$route.query.operator) {
      this.operator = this.$route.query.operator
    }
    if (this.$route.query.deliverDate) {
      this.deliveryDateArr.forEach(item => {
        if (this.$route.query.deliverDate === item.id) {
          this.dateData = item
        }
      })
    }
    this.setshowConfig()
    this.initData()
  },
  computed: {
    ...mapState({
      showConfig: state => {
        return state.listDisplaySet.showConfig
      }
    })
  },
  watch: {
    showConfig: {
      handler (val, oldVal) {
        this.pagination.pageSize = Number(val.max) || 15
        // 判定重复
        if (oldVal.fields && val.fields && oldVal.searchFields && val.searchFields) {
          this.modifyShowConfig()
        }
      }
    },
    searchPositionId: {
      handler (val, oldVal) {
        if (val !== oldVal) {
          this.getApplicationList()
        }
      }
    },
    $route: {
      handler (val, oldVal) {
        if (val.query.operator !== oldVal.query.operator) {
          if (!val.query.operator) {
            this.operator = 'Delivered'
          } else {
            this.operator = val.query.operator === 'ALL' ? '' : val.query.operator
          }
          this.pagination.current = 1
          this.getApplicationList()
        }
      }
    }
  },
  methods: {
    ...mapMutations('listDisplaySet', ['SET_FIELD']),
    filterBtn,
    recordBtn,
    goPositionDetail (item) {
      this.$router.push(`/position/positionEditing?positionId=${item.positionId}&searchType=${item.hrSiteType === 'VENDOR' ? 'PERSONAL' : 'COMPANY'}&enterpriseId=${item.enterpriseId}&sourcePid=${item.sourcePid}`)
    },
    getStatusName (text) {
      this.dataList && this.dataList.forEach(item => {
        if (item.key === text) {
          text = item.name
        }
      })
      return text
    },
    async getResumeData (record) { // 获取简历标准数据
      let res = await resumeInfo({ id: record.id, positionId: record.positionId })
      if (res.code === 200) {
        // 处理表单数据并传递给页面
        this.resumeData = res.data
        this.isshowResume = true
      } else {
        this.$message.error(res.message)
      }
    },
    recommedResume (flag, record, type) {
      // this.resumeData = record
      if (record) {
        this.positionInfo = record
        this.positionId = record.positionId
        this.id = record.id
        this.enterpriseId = record.enterpriseId
        this.getResumeData(record)
      } else {
        this.positionId = ''
        this.enterpriseId = ''
        this.resumeData = {}
        this.positionInfo = {}
      }
      this.isshowResume = flag
      // }
      if (type) {
        this.getApplicationList()
      }
    },
    initData () {
      this.getSearchOptions()
    },
    async getSearchOptions (flag) {
      let res = await recommendQueryConditions({ confingType: 'candidate' })
      if (res.code === 200) {
        this.searchListArr = res.data || []
        this.searchListArr.some((element, index) => {
          if (element.type === 'treeSelect') {
            let arr = this.resizeTree(element.treeData, 'id')
            this.$set(this.searchListArr[index], 'treeData', arr)
          }
        })
        this.$nextTick(() => { // 页面搜索options加载完毕后处理数据
          if (flag && JSON.stringify(this.resumeField) !== '{}') {
            this.$refs.TableOperate.resetSearch() // 设置搜索项后重新根据表单获取列表数据
          } else if (!flag) {
            this.setInptData() // 设置初始化route值
          }
        })
      }
    },
    setRoute (field, title, type) {
      if (this.$route.query[field] && (!type || !this.searchType) && this.searchListArr.some(item => item.id === field)) { // 职位界面跳转过来
        this.$set(this.valueFileds, field, this.$route.query[field])
        return true
      } else if (this.$route.query[field]) {
        this.unFieldList.push({ id: field, name: title })
        this.$set(this.unField, field, this.$route.query[field])
      }
    },
    async setInptData () { // 设置初始化route值，设置完后组件会自动刷新当前页面列表数据
      if (!this.setRoute('candidateUserId', '候选人ID') && !this.setRoute('positionId', '职位ID') && !this.setRoute('categoryId', '职能类别ID') && !this.setRoute('enterpriseId', '单位ID', true)) {
        this.$refs.TableOperate.resetSearch() // 设置搜索项后重新根据表单获取列表数据
      }
      // if ((this.$route.query.positionName || this.$route.query.enterpriseId) && !this.searchType && this.searchListArr.some(item => item.id === 'enterpriseId')) { // 职位界面跳转过来
      //   this.valueFileds = {
      //     positionName: this.$route.query.positionName,
      //     enterpriseId: this.$route.query.enterpriseId
      //   }
      // } else {
      //   this.unFieldList.push({ id: 'enterpriseId', name: '企业ID' })
      //   this.unFieldList.push({ id: 'positionName', name: '职位名称' })
      //   this.$set(this.unField, 'enterpriseId', this.$route.query.enterpriseId)
      //   this.$set(this.unField, 'positionName', this.$route.query.positionName)
      // }
    },
    controlData (data) {
      return data.map(item => {
        return { id: item.id || item.userId, name: item.name }
      })
    },
    filterField (item, record) {
      if (!item.hasLink) return
      this.pagination.current = 1
      if (this.searchListArr.some(element => {
        return element.id === item.path
      })) {
        this.valueFileds = {}
        this.$set(this.valueFileds, item.path, eval('record.' + item.path))
      } else {
        if (!this.unFieldList.some(val => val.id === item.key)) {
          this.unFieldList.push({ id: item.key, name: item.title })
        }
        this.$set(this.unField, item.key, eval('record.' + item.key))
        this.getApplicationList()
      }
    },
    closeOneField (id) {
      if (this.unField[id]) {
        this.$set(this.unField, id, '')
        this.getApplicationList()
      } else {
        this.valueFileds = {}
        this.$set(this.valueFileds, id, '')
      }
    },
    setPosition (positionId) {
      if (this.searchListArr.some(element => {
        return element.id === 'positionId'
      })) {
        this.valueFileds = {
          positionId
        }
        this.$set(this.valueFileds, 'positionId', positionId)
      } else {
        if (!this.unFieldList.some(val => val.id === 'positionId')) {
          this.unFieldList.push({ id: 'positionId', name: '职位ID' })
        }
        this.$set(this.unField, 'positionId', positionId)
        this.getApplicationList()
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    deleteData (ids) {
      ids = ids.split(',')
      let Tmp = this.data.filter(item => {
        return !ids.includes(item.id)
      })
      if (Tmp.length === 0) {
        this.getApplicationList()
      } else {
        this.data = Tmp
      }
    },
    async batchOperation (operator, ids) {
      this.loading = true
      let params = {
        ids,
        operator
      }
      let res = await applicationOperator(params)
      if (res.code === 200) {
        this.getApplicationList()
        this.$emit('getCard')
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
      this.loading = false
    },
    resizeTree (arr, field = 'id', key = 0) {
      if (!Array.isArray(arr)) return
      return arr.map((item, index) => {
        let treekey = `${key}-${index}`
        return { title: item.name, value: item[field], key: item[field], id: item[field], children: this.resizeTree(item.children, field, treekey) }
      })
    },
    async setshowConfig () {
      let res = await applicationShowConfig()
      if (res.code === 200) {
        if (res.data && res.data.fields) {
          res.max = res.data.max
          this.pagination.pageSize = res.data.max
          this.fieldsTmp = []
          this.unFieldList = []
          res.data.fields.forEach(item => {
            if (item.checked) {
              if (item.key === 'operatorStatus') {
                this.fieldsTmp.push({ title: item.value, dataIndex: item.key, key: item.key, scopedSlots: { customRender: item.key }, hasLink: item.hasLink })
              } else {
                this.fieldsTmp.push({ title: item.value, dataIndex: item.key, key: item.key, scopedSlots: { customRender: item.key }, hasLink: item.hasLink, path: item.path })
              }
              this.unFieldList.push({ id: item.path, name: item.value })
            }
          })
          this.SET_FIELD(res.data)
        }
      } else {
        this.$message.error(res.message)
      }
      if (!this.$route.query.positionId && !this.$route.query.candidateUserId && !this.$route.query.enterpriseId && !this.$route.query.categoryId) {
        this.getApplicationList()
      }
    },
    async modifyShowConfig () {
      // let fields = this.showConfig.fields.filter(item => item.checked)
      let res = await addOrModifyShowConfig(this.showConfig)
      if (res.code === 200) {
        this.fieldsTmp = []
        this.showConfig.fields.forEach(item => {
          if (item.checked) {
            if (item.key === 'operatorStatus') {
              this.fieldsTmp.push({ title: item.value, dataIndex: item.key, key: item.key, scopedSlots: { customRender: item.key }, hasLink: item.hasLink })
            } else {
              this.fieldsTmp.push({ title: item.value, dataIndex: item.key, key: item.key, scopedSlots: { customRender: item.key }, hasLink: item.hasLink, path: item.path })
            }
            this.unFieldList.push({ id: item.path, name: item.value })
          }
        })
        this.getSearchOptions(true)
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
    },
    clearSearch () {
      this.unField = {}
      this.$refs.TableOperate.clearSearch()
    },
    chooseDeliveryDate (item) {
      this.pagination.current = 1
      this.deliverDate = item.id === 'all' ? '' : item.id
      this.getApplicationList()
    },
    searchFormValue (item) {
      item.gender = item.gender === 'all' ? '' : item.gender
      this.resumeField = item
      this.pagination.current = 1
      this.getApplicationList()
    },
    editResume (record) {
      let list = this.data.map((item, index) => item.userId)
      let deliveryList = this.data.map((item, index) => item.id)
      let positionList = this.data.map((item, index) => item.positionId)
      let enterpriseIdList = this.data.map((item, index) => item.enterpriseId)
      let obj = {
        positionList,
        list,
        deliveryList,
        path: this.$route.path,
        fullPath: this.$route.fullPath,
        enterpriseIdList
      }
      sessionStorage.setItem('resumeList', JSON.stringify(obj))
      this.$router.push(`/resume/resumeView?id=${record.id}&positionId=${record.positionId}&enterpriseId=${record.enterpriseId}`)
    },
    changePage (current, pageSize) {
      this.$set(this.pagination, 'current', current)
      this.getApplicationList()
    },
    async getApplicationList () {
      this.loading = true
      this.selectedRowKeys = []
      let params = {
        max: this.pagination.pageSize,
        offset: (this.pagination.current - 1) * this.pagination.pageSize,
        queryFilter: {
          // operator: this.operator,
          deliverDate: this.deliverDate,
          ...this.unField,
          ...this.resumeField
        }
      }
      if (this.searchPositionId) {
        params.searchType = this.searchType
        params.queryFilter.positionId = this.searchPositionId
      }
      params.queryFilter.status = this.operator
      let res = await applicationList(params)
      if (res.code === 200) {
        this.data = res.data.items
        this.$set(this.pagination, 'total', res.data.totalCount)
        this.$emit('count', res.data.totalCount)
      } else {
        this.$message.error(res.message)
      }
      this.loading = false
    },
    setRowClassName (record, index) {
      return index % 2 === 0 ? 'grey' : ''
    }
  },
  beforeDestroy () {
    this.SET_FIELD({})
  }
}
</script>

<style lang="stylus" scoped>
@import '../../styles/var.styl'
.CandidateTable
// .ant-table-tbody > tr > td
  background #fff
  // 表格头部公共写法
  :global(.ant-table-title)
    padding 0
  :global(.ant-table-thead th)
    white-space nowrap
    background none
    padding 0
  :global(.ant-table-thead .ant-table-header-column)
    display inline-block
    width calc(100% - 16px)
    padding 5px 8px
    margin 5px 8px
    border-right 1px solid borderColor
  :global(.ant-table-thead th:first-child .ant-table-header-column)
  :global(.ant-table-thead th:last-child .ant-table-header-column)
    border-right none
  :global(.ant-table-tbody >tr >td)
    white-space nowrap
    padding 7px 16px
    vertical-align top
    >p
      white-space normal
      width 256px
      max-width 256px
      overflow : hidden;
      text-overflow: ellipsis;
      display -webkit-box
      -webkit-line-clamp 3 // 规定几行显示省略号
      -webkit-box-orient vertical
  :global(.grey)
    background var(--light-grey)
  .updateText
    cursor pointer
    margin 0
    font-weight 600
  .update
    // visibility hidden
    margin 6px 0 0
    span
      display none
      cursor pointer
      padding 0 0 0 4px
      color var(--blue-500)
      &:first-child
        padding-left 0
      &:last-child
        color errorColor
        &:after
          height 0
      &:after
        content ''
        vertical-align middle
        background borderColor
        display inline-block
        height 14px
        width 1px
        margin-left 4px
  :global(.ant-table-row)
    margin 0 12px
  .status
    padding 0 6px
    color #fff
    // border-radius 4px
  .bgBlue
    background var(--blue-500)
  .bgred
    background errorColor
  .grey
    background textDisable
  .red
    color errorColor
  .blue
    color var(--blue-500)
  .green
    background lightGreen
    color #fff
    border none
:global(.ant-table-row:hover)
  .update
    >span
      // visibility visible
      display inline-block
.point
  color var(--blue-500)
  cursor pointer
</style>
